<template>
  <div class="container">
    <div class="header">
      <el-input
        v-model="searchQuery"
        placeholder="请输入菜品名称"
        prefix-icon="el-icon-search"
        clearable
        @input="handleSearchInput"
      ></el-input>
      <div class="three">
        <el-link type="danger" class="onetap">批量删除</el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link
          type="primary"
          class="onetap"
          @click="handleBatchAction('start')"
          >批量启售</el-link
        >
        <el-divider direction="vertical"></el-divider>
        <el-link type="danger" class="onetap" @click="handleBatchAction('stop')"
          >批量停售</el-link
        >
        <el-button icon="el-icon-plus" @click="handleAdddish"
          >新建菜品</el-button
        >
      </div>
    </div>
    <el-table ref="multipleTable" :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="菜品名称"> </el-table-column>
      <el-table-column label="图片">
        <template v-slot="{ row }">
          <el-image
            style="width: 50px; height: 50px"
            :src="`${env}/common/download?name=${row.image}`"
            :preview-src-list="[`${env}/common/download?name=${row.image}`]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="菜品分类"> </el-table-column>
      <el-table-column prop="price" label="售价">
        <template v-slot="{ row }">
          {{ formatPrice(row.price) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="售卖状态">
        <template v-slot="{ row }">
          {{ row.status ? "启售" : "停售" }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后操作时间"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-link type="primary">修改</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link type="primary" slot="reference" @click="handle(row)">
            {{ row.status ? "停售" : "启售" }}
          </el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link type="danger" @click="bianji(row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <Pagination
        prev-text="1111"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.page"
        :page-size="pageInfo.pageSize"
        :total="total"
      />
    </div>
  </div>
</template>
  <script>
import { getDish, change, getList } from "@/api/caipin";
import addDish from "@/views/caipin/addDish.vue";
import Pagination from "@/components/Pagination/index.vue";
export default {
  components: { addDish, Pagination },
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      input: "",
      searchQuery: "",
      tableData: [],
      pageInfo: {
        page: 1,
        pageSize: 10,
      },
      total: 0,
      searchTimer: null,
    };
  },
  watch: {
    // 监听搜索关键词变化（备用方案）
    searchQuery(newVal) {
      this.handleSearch(newVal);
    },
  },
  created() {
    this.init();
  },
  methods: {
    handleBatchAction(actionType) {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning("请先选择要操作的菜品");
        return;
      }
      const ids = selectedRows.map((row) => row.id);
      const newStatus = actionType === "start" ? 1 : 0;
      this.$confirm(
        `确定要${actionType === "start" ? "启售" : "停售"}选中的菜品吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        try {
          await change({ ids: ids.join(",") }, newStatus);
          this.$message.success(
            `${actionType === "start" ? "启售" : "停售"}成功`
          );
          this.init(); // 刷新表格数据
        } catch (error) {
          this.$message.error(
            `${actionType === "start" ? "启售" : "停售"}失败`
          );
        }
      });
    },
    handleAdddish() {
      getList({ type: 1 }).then(() => {
        this.$router.push({ name: "addDish" });
      });
    },
    formatPrice(price) {
      const nextprice = String(price).slice(0, -2);
      return `￥${nextprice}`;
    },
    async init() {
      try {
        const params = {
          ...this.pageInfo,
          name: this.searchQuery.trim(), // 添加搜索参数
        };

        const res = await getDish(params);
        this.tableData = res.data.records;
        this.total = res.data.total;
      } catch (error) {
        console.error("获取员工列表失败:", error);
      }
    },
    handleSearchInput() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.pageInfo.page = 1; // 重置到第一页
        this.init();
      }, 300);
    },
    handleSizeChange(val) {
      this.pageInfo.page = 1;
      this.pageInfo.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.pageInfo.page = val;
      this.init();
    },
    handle(row) {
      change({ ids: row.id }, +!row.status).then(() => {
        this.$message.success("修改状态成功");
        this.init();
      });
    },
    bianji(id) {
      this.$router.push({ name: "bianjiEmployee", params: { id: id } });
    },
  },
};
</script>
  <style lang="scss" scoped>
.container {
  padding: 33px;
  .header {
    display: flex;
    justify-content: space-between;
    .el-input {
      width: 250px;
    }
    .three {
      display: flex;
      .onetap {
        padding-right: 20px;
        padding-left: 20px;
      }
    }
  }
  .el-table {
    margin-top: 20px;
  }
  .footer {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
  